﻿#region Copyright & licence

// This file is part of Refix.
// 
// Refix is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
// 
// Refix is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License along with Refix.  If not, see <http://www.gnu.org/licenses/>.
// 
// Copyright (C) 2010-11 David Musgrove and others.

#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

using Refix.Core.Options;
using Refix.Core.Properties;
using Refix.Core.Structure;

namespace Refix.Core.Commands
{
    public class Find : Command
    {
        private bool FindAll
        {
            get { return Options.Options.Any(o => o is All); }
        }

        protected override string HelpText
        {
            get { return ResourceDispenser.GetString("FIND_HELP"); }
        }

        public override bool Validate()
        {
            if (!base.Validate())
            {
                return false;
            }
            if (Options.Arguments.Count < 2 || Options.Arguments.Count > 3)
            {
                OutputWriter.WriteLine(OutputVerbosity.Quiet, ResourceDispenser.GetString("WRONG_NUMBER_OF_ARGUMENTS"));
                ShowHelp();
                return false;
            }
            return true;
        }

        public override bool Execute()
        {
            string solutionFile;
            int index = 0;
            if (Options.Arguments.Count == 3)
            {
                solutionFile = Options.Arguments[index++];
                FileInfo[] fileInfos =
                    new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles(solutionFile);
                if (fileInfos.Length != 1)
                {
                    OutputWriter.WriteLine(OutputVerbosity.Quiet,
                                       ResourceDispenser.GetString("SINGLE_SOLUTION_FILE_DOESNT_EXIST"));
                    return false;
                }
                solutionFile = fileInfos[0].FullName;
            }
            else
            {
                FileInfo[] fileInfos =
                    new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles("*" + FileExtensions.Solution);
                if (fileInfos.Length != 1)
                {
                    OutputWriter.WriteLine(OutputVerbosity.Quiet,
                                       ResourceDispenser.GetString("SINGLE_SOLUTION_MULTIPLE_SOLUTION_FILES"));
                    return false;
                }
                solutionFile = fileInfos[0].FullName;
            }
            string assembly = Options.Arguments[index++];
            string version = Options.Arguments[index];

            Structure.Solution solution = new SolutionHelper(GetLocalRepository()).GetSolution(solutionFile);
            if (solution == null)
            {
                return false;
            }

            solution.Projects.RemoveAll(p => !p.Contains(assembly, version));
            foreach (Project project in solution.Projects)
            {
                RemoveProjects(assembly, version, project.ProjectReferences);
                RemoveReferences(assembly, version, project.References);
            }
            solution.Projects.RemoveAll(p => p.References.Count == 0
                                             && p.ProjectReferences.Count == 0);

            new ConsoleVisualizationStructureVisitor { IsPlain = Options.Options.Any(o => o is Plain) }.Visit(solution);
            return true;
        }

        static private void RemoveReferences(string assembly, string version, List<BinaryReference> references)
        {
            references.ForEach(r => RemoveReferences(assembly, version, r.References));
            references.RemoveAll(r =>
                                 (!string.Equals(r.Name, assembly, StringComparison.OrdinalIgnoreCase) ||
                                  r.OriginalVersion != version)
                                 && !r.References.Contains(assembly, version));
        }

        private void RemoveProjects(string assembly, string version, List<Project> projectReferences)
        {
            projectReferences.RemoveAll(p => !FindAll || !p.Contains(assembly, version));
        }
    }
}